package com.subalien.client;

import java.util.Map;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.events.SubmitValuesEvent;
import com.smartgwt.client.widgets.form.events.SubmitValuesHandler;
import com.smartgwt.client.widgets.form.fields.SpacerItem;
import com.smartgwt.client.widgets.form.fields.SubmitItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.subalien.client.dto.LoginInfoDto;
import com.subalien.client.util.ServiceSingleton;

public class NewPlayerForm extends DynamicForm implements SubmitValuesHandler {
	private LoginInfoDto loginInfoDto = null;

	public NewPlayerForm(final LoginInfoDto loginInfoDto) {
		super();

		this.loginInfoDto = loginInfoDto;

		init();
		build();
		preFill();
	}

	private void init() {
		setNumCols(2);
		setAutoFocus(true);
		setSaveOnEnter(true);
		setWidth(200);

		addSubmitValuesHandler(this);
		//setCellBorder(1); // for debug only
	}

	private void build() {
		SpacerItem spacerItem = new SpacerItem();

		TextItem usernameItem = new TextItem("playername", "Nick");
		usernameItem.setRequired(true);

		SubmitItem submit = new SubmitItem("submit", "Create");
		submit.setStartRow(false);
		submit.setAlign(Alignment.RIGHT);

		setFields(usernameItem, spacerItem, submit);
	}

	private void preFill() {
		// to speed up debug
		//getItem("playername").setValue("newplayer");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onSubmitValues(SubmitValuesEvent event) {
		if (validate()) {
			Map<String, Object> map = getValues();

			final String playername;

			if (map.get("playername") != null) {
				playername = (String) map.get("playername");

				System.out.println("playername: " + playername);
				
				ServiceSingleton.getGameServiceAsyncInstance().createPlayer(loginInfoDto.getEmailAddress(), playername, new AsyncCallback<Long>() {
					@Override
					public void onSuccess(final Long playerId) {
						//SC.say("new player created");
						
						ServiceSingleton.getGameServiceAsyncInstance().createSubmarine(playerId, new AsyncCallback<Void>() {
							@Override
							public void onSuccess(Void result) {
								//SC.say("new player created");
								MainTool.getGameTool().loadSubmarine(playerId);
								MainTool.getNavigationTool().build();
								MainTool.getGameTool().drawPlayerLabel(playername);
							}

							@Override
							public void onFailure(Throwable caught) {
								caught.printStackTrace();
							}
						});
					}

					@Override
					public void onFailure(Throwable caught) {
						caught.printStackTrace();
					}
				});
			}
		}
	}
}
